import fs from 'fs';

interface PathInfo {
    isDirectory: boolean;
    size: number;
    md5: string | null;
}


// 获取文件信息：【大小、是否为文件夹、md5】
async function getPathInfo(path: string, calcMd5 = true): Promise<PathInfo | null> {
    return new Promise(function (resolve) {
        fs.stat(path, (err: any, stats: any) => {
            if (err) {
                resolve(null);
            } else {
                const info = {
                    isDirectory: !!stats && stats.isDirectory(),
                    size: stats.size / 1000,
                    mtime: stats.mtime,
                    md5: null
                };

                if (calcMd5 && !info.isDirectory) {
                    info.md5 = require('crypto').createHash('md5').update(fs.readFileSync(path)).digest('hex');
                }
                resolve(info);
            }
        });
    });
}


export default getPathInfo;
